package controllers;

import java.rmi.RemoteException;

import play.data.validation.Error;
import play.data.validation.Required;
import play.i18n.Messages;

import services.BookApiService;
import services.impl.GoogleBookApiService;
import controllers.CRUD.ObjectType;
import exceptions.BookNotFoundException;
import exceptions.FindBookException;
import exceptions.NotUniqueBookException;
import models.Author;
import models.Book;

public class Books extends CRUD {
	
	public static void load(@Required String isbn) {
		Book object = new Book();
		if (validation.hasErrors()) {
			renderArgs.put("error", "isbn number is required");
			render("Books/blank.html", object);
		}
		if (!validation.hasErrors()) {
			Book existing = Book.find("byIsbn", isbn).first();
			if (existing != null){
				object = existing;
				renderArgs.put("error", "Book already in library");
				render("CRUD/show.html", object);
			}else{
				BookApiService bookServce = new GoogleBookApiService();
				try {
					object = bookServce.findBookByIsbn(isbn);
					for(Author a : object.authors){
						a.saveOrLoad();
					}
					object.create();
					render("CRUD/show.html", object);
				} catch (FindBookException e) {
					renderArgs.put("error", "Cannot find the book");
					render("Books/blank.html", object, isbn);
				} catch (RemoteException e) {
					renderArgs.put("error", "Cannot access a service");
					render("Books/blank.html", object, isbn);
				}
			}
		}
	}
}
